package com.kang.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.kang.base.LoginDataBase;
import com.kang.entity.SysUser;
import com.kang.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;


@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        SysUser user = common(request);
        ThreadLocalUtil.addCurrentUser(user);

        HandlerMethod handlerMethod=(HandlerMethod)handler;
        //判断如果请求的类是swagger的控制器，直接通行。
        handlerMethod.getBean();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        ThreadLocalUtil.remove();
    }

    public SysUser common(HttpServletRequest request) {
        String token = request.getHeader("token");
        String tokenInfo = stringRedisTemplate.opsForValue().get("login:token:" + token);
        LoginDataBase loginDataBase = JSONObject.parseObject(tokenInfo, LoginDataBase.class);
        if (Objects.isNull(loginDataBase)) {
            return null;
        } else {
            return loginDataBase.getUser();
        }
    }
}